<?php

/*
user_model:负责用户控制功能，包括：
用户登录检查
用户权限检查
管理用户，增、删、查、改

登录或检查登录时连接数据库
*/

class User_model extends CI_Model
{

	private $table;
	public $error;

	function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');	//测试选择数据库
		$this->test_database->test();
		$this->load->database($this->test_database->get_db());
		//载入核心类
		$this->load->library('form_validation');
		$this->load->library('session');
		//载入辅助类
		$this->load->helper('hasher');	//加密函数
		//载入本地语言文件
		$this->lang->load('form_validation','chinese');
		//Init the values
		$this->table = 'users';
		$this->TABLE = @$this->table;
	}

	//检查用户通过后，更新COOKIE
	private function loginedCookie($data, $expire=180000, $secure=false)
	{
		foreach ($data as $k=>$v)
		{
			$cookie = array(
				'name'	=>	$k,
				'value'	=>	$v,
				'expire'	=>	$expire,
			);
			$this->input->set_cookie($cookie);
		}
	}

	//检查登录用户
	public function checkLogin()
	{
		if (TRUE == $this->input->post('login'))
		{
			$this->form_validation->set_rules('username', '账户', 'trim|required|min_length[5]|max_length[20]|alpha_dash|xss_clean');
			$this->form_validation->set_rules('password', '密码', 'trim|required|xss_clean');
			if (TRUE == $this->form_validation->run())
			{
				if ($uid = $this->_checkUser($this->input->post('username'), $this->input->post('password')))
				{
					return $uid;
				}
				return 'LOGIN_ERR';
			}
			return false;
		}
	}

	//检查登录用户
	public function checkLoginedUser()
	{
		if ($this->_checkUser($this->input->cookie('username'), $this->input->cookie('password'), true, true))
		{
			return true;
		}
		return false;
	}

	//检查用户方法
	//验证成功返回user_id
	private function _checkUser($username, $password, $logined = false, $strict = false)
	{
		$query = $this->db->get_where('users', array('username'=>$username), 1);
		if (1 == $query->num_rows()) {
			foreach ($query->result() as $v)
			{
				if ($logined)
				{
					if ($password == $v->password)
					{
						//严格验证
						if ($strict)
						{
							$uid = $this->input->cookie('user_id');
							if ($uid != $v->user_id)
							{
								return false;
							}
						}
						$user = array(
							'user_id'	=>	$v->user_id,
							'username'	=>	$v->username,
							'realname'	=>	$v->realname,
							'password'	=>	$password,
							'database'	=>	$this->test_database->get_db()
						);
						$this->loginedCookie($user, 180000, true);
						return $user['user_id'];
					}
				}
				else
				{
					if (hasher($password, $v->password))
					{
						//严格验证
						if ($strict)
						{
							$uid = $this->input->cookie('user_id');
							if ($uid != $v->user_id)
							{
								return false;
							}
						}
						$user = array(
							'user_id'	=>	$v->user_id,
							'username'	=>	$v->username,
							'realname'	=>	$v->realname,
							'password'	=>	$v->password,
							'database'	=>	$this->test_database->get_db()
						);
						$this->loginedCookie($user, 180000, true);
						return $user['user_id'];
					}
				}
			}
		}
		$this->error = '账户 或 密码 错误，请重试！';
		return false;
	}

	//获得工作环境
	public function get_envrionment()
	{
		return $this->test_database->get_environment();
	}

	//登出删除COOKIE
	public function logout()
	{
		$user = array(
			'user_id'	=> '',
			'username'	=> '',
			'realname'	=> '',
			'password'	=> '',
			'database'	=> ''
		);
		$this->loginedCookie($user, -1800, false);
	}

	//创建一个用户
	public function createUser()
	{
		//验证表单数据
		$this->form_validation->set_rules('username', '账户', 'trim|required|min_length[5]|max_length[20]|alpha_dash|xss_clean|unique[User_model]');
		$this->form_validation->set_rules('password', '密码', 'required|min_length[5]|max_length[20]|matches[passconf]');
		$this->form_validation->set_rules('passconf', '密码确认', 'required|max_length[20]');
		$this->form_validation->set_rules('realname', '真实姓名', 'trim|required|min_length[2]|max_length[12]|xss_clean');
		$this->form_validation->set_rules('phone', '联系方式', 'trim|required|min_length[8]|max_length[14]|numeric');
		if (true == $this->form_validation->run()) {
			$user['username'] = $this->input->post('username');
			$user['password'] = hasher($this->input->post('password'));
			$user['realname'] = $this->input->post('realname');
			$user['phone'] = $this->input->post('phone');
			$user['create_date'] = time();
			//创建一条用户数据
			$this->db->insert('users', $user);
			//print_r($user);
			return true;
		}
		return false;
	}

	//更新用户
	public function updateUser($uid, $type)
	{
		//验证用户是否存在
		if ($this->getUser($uid))
		{
			switch ($type) {
				case 'base':
					//更新基本信息
					$this->form_validation->set_rules('phone', '联系方式', 'trim|required|min_length[8]|max_length[14]|numeric');
					break;
				case 'secure':
					//更新安全信息
					if ($this->input->cookie('user_id') != 1 || $uid == 1)
					{					
						$this->form_validation->set_rules('pass_old', '原始密码', 'required|min_length[5]|max_length[20]|checkSelf');
					}
					$this->form_validation->set_rules('pass_new', '新密码' ,'required|min_length[5]|max_length[20]|matches[passconf]');
					$this->form_validation->set_rules('passconf', '密码确认', 'required|max_length[20]');
					break;
				case 'rights':
					//更新权限信息
					$this->form_validation->set_rules('right_ids[]', '权限', 'required|checkRightsForm');
					break;
				default:
					return false;
			}
			if (true == $this->form_validation->run())
			{
				//表单数据有效，分类获取格式化后的数据
				switch ($type) {
					case 'base':
						$user['phone'] = $this->input->post('phone');
						break;
					case 'secure':
						$user['password'] = $this->input->post('pass_new');
						break;
					case 'rights':
						break;
				}
				if ('secure' == $type)
				{
					$password = $user['password'];
					$user['password'] = hasher($user['password']);
				}
				$this->db->where('user_id', $uid);
				$this->db->update('users', $user);
				if (1 == $this->db->affected_rows())
				{
					if ('secure' == $type)
					{
						$user = array(
							'password'	=>	$password
						);
						$this->loginedCookie($user, 180000, false);
					}
					return true;
				}
			}
		}
		return false;
	}

	//禁用用户
	function delUser($uid)
	{
		$data = array(
			'del_flg'	=>	1
		);
		$this->db->where('user_id', $uid);
		$this->db->update('users', $data);
		if ($this->db->affected_rows())
		{
			return true;
		}
		return false;
	}

	//恢复用户
	function recoverUser($uid)
	{
		if (1 == $uid)
		{
			return false;
		}
		$data = array(
			'del_flg'	=> 0
		);
		$this->db->where('user_id', $uid);
		$this->db->update('users', $data);
		if (1 == $this->db->affected_rows())
		{
			return true;
		}
		return false;
	}

	//返回用户可访问的主菜单
	//重构于 2012-10-29 16:06
	public function userMenus($menus, $right_ids, $menu_index=FALSE)
	{
		if (0 == $right_ids[0] || 1 == $right_ids[0])
		{
			return $menus;
		}
		$new_menus = array();
		foreach ($menus as $key=>$menu)
		{
			if (in_array($menu['right_id'], $right_ids))
			{
				$new_menus[] = $menu;
			}
		}
		return $new_menus;
	}

	//判断是否是超级管理员
	public function isSuperuser()
	{
		if (1 == $this->input->cookie('user_id')) {
			return true;
		}
		return false;
	}

	//提供给表单验证扩展{../libraries/MY_Form_valiation.php}使用的函数
	//单独使用之前请先格式化{$username}为合法值
	public function checkUniUser($username)
	{
		$query = $this->db->get_where('users', array('username'=>$username));
		if (1 == $query->num_rows()) {
			return false;
		}
		return true;
	}

	public function unique($username)
	{
		return $this->checkUniUser($username);
	}

	//以下是获得数据的 get 方法
	//获得一个用户信息的方法
	//2013-01-11
	public function get_user($type, $user_id='', $username='', $password='')
	{
		
		if ('login' == $type)
		{
			$this->db->where('username', $username);
			if ($query = $this->db->get($this->TABLE))
			{
<<<<<<< HEAD
				if (1 == $query->num_rows())
=======
				if ($query->num_rows() == 1)
>>>>>>> ff5f7ef6de592146b376adc8ed0c004b06507151
				{
					$user = $query->row_array();
					if (hasher($password, $user['password']))
					{
						//将数据库环境插入到数组
						$user['database'] = $this->test_database->get_db();
						$user['environment'] = $this->test_database->get_environment();
						return $user;
					}
				}
<<<<<<< HEAD
				$this->error = 'LOGIN_ERROR';
=======
				else
				{
					$this->error = 'LOGIN_ERROR';
				}
>>>>>>> ff5f7ef6de592146b376adc8ed0c004b06507151
			}
			else
			{
				$this->error = 'SYS_ERROR';
			}
		}
		else if ('check' == $type)
		{
			$where = array(
				'username'	=> $username,
				'password'	=> $password,
				);
			if ($query = $this->db->where($where)->get($this->TABLE))
			{
				if ($query->num_rows() == 1)
				{
					$user = $query->row_array();
					$user['database'] = $this->test_database->get_db();
					$user['environment'] = $this->test_database->get_environment();
					return $user;
				}
				else
				{
					$this->error = 'CHECK_ERROR';
				}
			}
			else
			{
				$this->error = 'SYS_ERROR';
			}
		}
		else if ('user_id' == $type)
		{
			$this->db->where('user_id', $user_id);
			if ($query = $this->db->get($this->TABLE))
			{
				if ($query->num_rows() == 1)
				{
					return $user;
				}
				else
				{
					$this->error = 'SYS_ERROR';
				}
			}
			else
			{
				$this->error = 'SYS_ERROR';
			}
		}
		else
		{
			$this->error = 'SYS_ERROR';
		}
		return FALSE;

	}

	//获得一个用户的信息
	//返回值为数组
	public function getUser($uid, $check_only = false)
	{
		if ( false === $check_only )
		{
			if (false === $uid)
			{
				$query = $this->db->get_where('users',array('user_id'=>$this->input->cookie('user_id')),1);
			}
			else
			{
				$query = $this->db->get_where('users',array('user_id'=>$uid),1);
			}
			if (1 == $query->num_rows()) {
				$user = $query->result();
				$user = get_object_vars($user[0]);
				return $user;
			}
			return false;
		}
		else
		{
			if (is_array($uid))
			{
				foreach ($uid as $v)
				{
					$query = $this->db->get_where('users', array('user_id'=>$v), 1);
					if (1 != $query->num_rows())
					{
						return false;
					}
				}
			}
			else
			{
				$query = $this->db->get_where('users', array('user_id'=>$uid), 1);
				if (1 != $query->num_rows())
				{
					return false;
				}
			}
			return true;
		}
	}

	//获得所有用户列表
	public function getUsers($deleted = false)
	{
		if (false === $deleted)
		{
			$this->db->where('del_flg', '0');
			$this->db->order_by("create_date", "ASC");
			$users = $this->db->get('users')->result();
			unset($users[0]);
			return $users;
		}
		else
		{
			$this->db->where('del_flg', '1');
			$this->db->order_by('create_date', 'ASC');
			$users = $this->db->get('users')->result();
			return $users;
		}
	}

	function getUserRights($uid)
	{
		$query = $this->db->get_where('users', array('user_id'=>$uid), 1);
		foreach ($query->result() as $v){
			return $rights = $v->rights;
		}
	}

}